package com.gopay.webtest.controller;

import java.io.IOException;
import java.util.Date;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang.time.StopWatch;
import org.dom4j.DocumentException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.gopay.webtest.controller.base.BaseController;
import com.gopay.webtest.util.BaseSign;
import com.gopay.webtest.vo.CommonResp;
import com.gopay.webtest.vo.ExPayCacheMock;
import com.gopay.webtest.vo.PayInfo;
import com.gopay.webtest.xml.XmlDao;

import net.sf.json.JSONObject;

/**
 * 
 * @ClassName: WXPayController
 * @Description: 微信支付
 * @author zhoutong
 * @date 2016年8月5日 下午6:06:45
 */
@SuppressWarnings("all")
@Controller
public class WXPayController extends BaseController {

    private static final String CHARSET_GBK = "1";

    @Resource(name = "paySignHandler")
    private BaseSign paySignHandler;

    private static Map<String, String> map = null;

    @Autowired
    public WXPayController(@Qualifier(value = "xmlDao") XmlDao xmlDao) {
        try {
            map = xmlDao.readData4Map("wxPay", "payapply");
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 
     * @Description: 微信支付提交
     * @return
     * @author zhoutong
     */
    @RequestMapping("/wxPay")
    public ModelAndView pay() {
        ModelAndView mav = new ModelAndView();
        PayInfo payinfo = getDefaultInfoFromXML();
        mav.setViewName("gopay.webtest.wxPay");
        mav.addObject("payInfo", payinfo);
        return mav;
    }

    /**
     * 
     * @Description: 刷新二维码
     * @return
     * @author zhoutong
     */
    @RequestMapping("/wxPayRefresh")
    public ModelAndView refresh() {
        ModelAndView mav = new ModelAndView();
        PayInfo payinfo = getDefaultInfoFromXML();
        mav.setViewName("gopay.webtest.wxPayRefresh");
        mav.addObject("payInfo", payinfo);
        return mav;
    }

    /**
     * 
     * @Description: 获取初始化数据
     * @return
     * @author Adimn
     */
    private PayInfo getDefaultInfoFromXML() {
        PayInfo payInfo = new PayInfo();

        payInfo.setMerchantID((String) map.get("merchantID"));
        payInfo.setBackgroundMerUrl((String) map.get("backgroundMerURL"));
        payInfo.setCurrencyType((String) map.get("currType"));
        payInfo.setTranDateTime(com.gopay.webtest.util.DateUtils.date2string(new Date(),
                com.gopay.webtest.util.DateUtils.DEFAULT_PATTERN));
        payInfo.setGopayServerTime(com.gopay.webtest.util.DateUtils.date2string(new Date(),
                com.gopay.webtest.util.DateUtils.DEFAULT_PATTERN));
        payInfo.setTranIP((String) map.get("tranIP"));
        payInfo.setVirCardNoIn((String) map.get("virCardNoIn"));
        payInfo.setAppId((String) map.get("appId"));
        return payInfo;
    }

    /**
     * 提交订单到支付宝
     * 
     * @param payInfo
     * @return
     */
    @RequestMapping("/wxPaySubmit")
    public ModelAndView paySubmit(PayInfo payInfo) {
        ModelAndView mav = new ModelAndView();
        String backgroundMerUrl = payInfo.getBackgroundMerUrl();
        if (backgroundMerUrl != null && !backgroundMerUrl.equals("")) {
            backgroundMerUrl = backgroundMerUrl + "?id=" + payInfo.getVerficationCode();
        }

        payInfo.setBackgroundMerUrl(backgroundMerUrl);

        StopWatch sw = new StopWatch();

        // 设置MD5加密字段
        try {
            sw.start();

            payInfo.setCallType(payInfo.getBuyerName());
            payInfo.setGoodsTag(payInfo.getMerRemark1());
            payInfo.setProductId(payInfo.getMerRemark2());

            paySignHandler.sign(payInfo.getTranCode() + "_" + payInfo.getVersion(), "signType", "signValue", payInfo, getRequest());
            sw.stop();
            logger.info("step1 time:" + sw.getTime());
            logger.info("后台notify密文值:" + payInfo.getSignValue());
        } catch (Exception e) {
            e.printStackTrace();
        }
        String signedValue = payInfo.getSignValue();
        if (null == signedValue) {
            // 加密操作失败,置返回码为身份认证md5加密失败
            payInfo.setRespCode("MR08");
            mav.setViewName("gopay.webtest.wxPay");
        } else {
            if (!payInfo.getCharset().equals("2")) {
                mav.setViewName("gopay.webtest.wxPayFormSubmit_gbk");
            } else {
                mav.setViewName("gopay.webtest.wxPayFormSubmit");
            }
        }
        mav.addObject("payInfo", payInfo);
        return mav;
    }
    

    /**
     * 
     * @Description: 二维码刷新提交
     * @param payInfo
     * @return 
     * @author zhoutong
     */
    @RequestMapping("/wxPayRefreshSubmit")
    public ModelAndView refreshSubmit(PayInfo payInfo) {
        ModelAndView mav = new ModelAndView();
        StopWatch sw = new StopWatch();
        // 设置MD5加密字段
        try {
            sw.start();
            paySignHandler.sign(payInfo.getTranCode() + "_" + payInfo.getVersion(), "signType", "signValue", payInfo, getRequest());
            sw.stop();
            logger.info("step1 time:" + sw.getTime());
            logger.info("后台notify密文值:" + payInfo.getSignValue());
        } catch (Exception e) {
            e.printStackTrace();
        }
        String signedValue = payInfo.getSignValue();
        if (null == signedValue) {
            // 加密操作失败,置返回码为身份认证md5加密失败
            payInfo.setRespCode("MR08");
            mav.setViewName("gopay.webtest.wxPayRefresh");
        } else {
            if (!payInfo.getCharset().equals("2")) {
                mav.setViewName("gopay.webtest.wxRefreshFormSubmit");
            } else {
                mav.setViewName("gopay.webtest.wxRefreshFormSubmit");
            }
        }
        mav.addObject("payInfo", payInfo);
        return mav;
    }
    
    /**
     * 
     * @Description:跳转到等待页面
     * @return 
     * @author zhoutong
     */
    @RequestMapping("/wxPayWait")
    public ModelAndView payWait() {
        ModelAndView mav = new ModelAndView();
        mav.setViewName("gopay.webtest.wxPayWait");
        return mav;
    }
    
    /**
     * 获取订单返回结果.
     * @param orderId
     * @return
     */
    @ResponseBody
    @RequestMapping("/getWXOrderResult")
    public String getOrderResult(String orderId) {
        CommonResp payinfo = (CommonResp) ExPayCacheMock.getObject(orderId);
        JSONObject json = new JSONObject();
        if (payinfo != null) {
            ///表明已经有通知了
            logger.info("respCode ==" + payinfo.getRespCode());
            if (payinfo.getRespCode() != null && payinfo.getRespCode().equals("0000")) {
                json.put("result", "1");
                return "1";
            } else {
                json.put("result", "2");
                //错误 --删不删缓存.....
                //return json.toString();
                return "2";
            }
        } else {
            json.put("result", "0"); //2失败   1 成功   0未获取到
        }
        logger.info("orderId=" + orderId + ",获取返回结果=" + json.getString("result"));
        
        return json.getString("result");
    }
}